package dijjer.io.xfer.http;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import dijjer.Dijjer;

public abstract class HTTPResponse {

	public static final String VERSION = "$Id: HTTPResponse.java 2 2008-03-21 14:33:03Z ian.clarke $";
	private final int _responseCode;
	private final String _responseMessage;
	private final String _type;
	private final Map _headers = new HashMap();

	protected HTTPResponse(int code, String message, String contentType) {
		_type = contentType;
		_responseCode = code;
		_responseMessage = message;
	}

	public void addHeader(String name, String value) {
		_headers.put(name, value);
	}

	public final void write(OutputStream out) throws IOException {
		out.write(getHeader());
		writeTo(out);
	}

	private byte[] getHeader() {
		StringBuffer header = new StringBuffer();
		header.append("HTTP/1.1 " + _responseCode + " " + _responseMessage + " " + HTTPServer.CRLF);

		header.append("Server: Dijjer" + HTTPServer.CRLF);
		header.append("Dijjer-Build: " + Dijjer.BUILD + HTTPServer.CRLF);
		header.append("Date: "+ new Date() + HTTPServer.CRLF);

		for (Iterator i = _headers.keySet().iterator(); i.hasNext();) {
			String name = (String) i.next();
			header.append(name + ": " + _headers.get(name) + HTTPServer.CRLF);
		}

		header.append("Content-Type: " + _type + HTTPServer.CRLF);
		header.append("Content-Length: " + getContentLength() + HTTPServer.CRLF);

		header.append(HTTPServer.CRLF);

		return header.toString().getBytes();
	}
	
	protected abstract long getContentLength();

	protected abstract void writeTo(OutputStream out) throws IOException;

}
